package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	sharedconfig "github.com/devops-smartbot/devops-smartbot/shared/config"
	"github.com/devops-smartbot/devops-smartbot/shared/logger"
	"github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/config"
	httpserver "github.com/devops-smartbot/devops-smartbot/services/api-gateway/internal/server/http"
	"go.uber.org/zap"
)

func main() {
	cfg := sharedconfig.MustLoad(os.Getenv("CONFIG_FILE"))

	log, err := logger.Init(cfg.App.Name, cfg.App.LogLevel)
	if err != nil {
		panic(fmt.Errorf("logger init: %w", err))
	}
	defer log.Sync() //nolint:errcheck

	gatewayCfg := config.FromShared(cfg)

	server := httpserver.New(gatewayCfg)

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	go func() {
		if err := server.Start(); err != nil && err != http.ErrServerClosed {
			log.Fatal("http server failed", zap.Error(err))
		}
	}()

	log.Info("api-gateway started", zap.Int("port", gatewayCfg.HTTPPort))

	<-ctx.Done()
	log.Info("shutdown signal received")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := server.Stop(shutdownCtx); err != nil {
		log.Error("failed to shutdown http server", zap.Error(err))
	}

	log.Info("api-gateway stopped")
}
